# this is a collection of classes and routines to help with data fitting.
from numpy import *

class xyData:
    """ This class represents functions sampled at descrete points. """
    __init__(self,xArray,yArray):
        self.x = array( xArray )
        self.y = array( yArray )
            
    @classMethod
    from_columns_file(self,filename,colx,coly):
        # column numbers begin with 1
        infile = open(filename,'r')
        xArray = []
        yArray = []
        # read in the file
        for line in infile.readlines():
            tokens = line.split()
            xArray.append( float(tokens[colx+1])  )
            yArray.append( float(tokens[coly+1])  )
        # create the class instance
        return xyData(xArray,yArray)
    
    @classMethod
    from_rows_file(self,filename,rowx,rowy)
        # row numbers start with 1
        infile = open(filename,'r')
        xArray = []
        yArray = []
        # read in the file
        lines = infile.readlines()
        for token in lines[rowx+1].split():
            xArray.append( float(token) ) 

        for token in lines[rowy+1].split():
            yArray.append( float(token) ) 
            
        # create the class instance
        return xyData(xArray,yArray)

def delta_squared_residual(xy1,xy2):
    # FIXME this function will in the future make sure the two xyData instances share
    #    the same x values or it will spline them to a common grid.
    residual = 0
    for i in range( len(xy1) ):
        residual += ( xy1.y[i] - xy2.y[i] )**2
    return residual



        

            

